﻿namespace Nello.Web
{
    using System;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;

    public class WebUtil
    {
        public static string BinPath(string filename)
        {
            return (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath + @"\" + filename);
        }

        public static T Current<T>()
        {
            object obj = HttpContext.Current.Session["global_user_key"];
            if (obj == null)
            {
                return default(T);
            }
            return (T) obj;
        }

        public static Pair GetFirstTable(string text)
        {
            return GetFirstTag("table", text);
        }

        public static Pair GetFirstTag(string tag, string text)
        {
            string regex = "<" + tag + @"\s*[^>]*>(.+?)</" + tag + ">";
            Match match = Regex.Match(text, regex, RegexOptions.Multiline | RegexOptions.IgnoreCase);
            Pair pp = new Pair();
            if (match.Groups.Count == 2)
            {
                pp.First = match.Groups[0].Value;
                pp.Second = match.Groups[1].Value;
                return pp;
            }
            pp.First = "";
            pp.Second = "";
            return pp;
        }

        public static Pair GetFirstTD(string text)
        {
            return GetFirstTag("td", text);
        }

        public static Pair GetFirstTR(string text)
        {
            return GetFirstTag("tr", text);
        }

        public static Pair GetTitle(string text)
        {
            return GetFirstTag("title", text);
        }

        public static string BinDirectory
        {
            get
            {
                return AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            }
        }

        public static string PageName
        {
            get
            {
                string[] paths = HttpContext.Current.Request.Url.Segments;
                return paths[paths.Length - 1];
            }
        }

        public static string WebSiteDirectory
        {
            get
            {
                return HttpContext.Current.Request.PhysicalApplicationPath;
            }
        }
    }
}

